import api from '@h5app/sheep/api'
import { H5_APP_SHA256_KEY } from '@h5app/sheep/interface/constants'
import { store } from '@h5app/sheep/store'
import { EncryptSha256 } from '@h5app/sheep/utils/encrypt/sha256'
import { computed } from 'vue'
import { useDingding, useLink, useRouter, useTips } from '@h5app/sheep/hooks'
import * as dd from 'dingtalk-jsapi' // 此方式为整体加载，也可按需进行加载

export type LoginParams = any

type LoginResponse = any

let isSync = false
export function useAuth() {
  const tips = useTips()
  const userStore = store.useUserStore()
  const router = useRouter()
  const ddLogin = useDingding()

  function settingUser(userResult: LoginResponse | undefined | null) {
    if (!userResult) return
    const { userLoginData, token } = userResult

    userStore.userInfo = userLoginData
    userStore.token = token
  }

  /** 账号密码登录 */
  const register = async (params: LoginParams) => {
    const data = Object.assign({}, params)

    data.password = EncryptSha256(
      `${data.username}-${data.phone}-${data.password}-${data.belongCompany}` || '',
      H5_APP_SHA256_KEY,
    )
    tips.showLoading()
    const result = await api.AuthRegister(data)

    if (result.success) {
      settingUser(result?.data)
    }

    tips.hideLoading()
  }

  const isLogin = computed(() => {
    return !!userStore.token
  })

  const line = useLink()
  const verifyLogin = () => {
    return new Promise((resolve, reject) => {
      if (!isLogin.value) {
        const fullPath = router.currentRouter.value?.$page.fullPath
        const [url = fullPath, params] = router.currentRouter.value?.$page.fullPath.split?.('?')

        router.push('register', {
          query: {
            redirect: encodeURIComponent(url),
            params: JSON.stringify(line.parseUrlParams(params)) || '',
          },
        })
        reject()
        return
      }
      resolve('')
    })
  }

  const refreshLogin = async () => {
    const userInfo = userStore.userInfo
    if (!userInfo?.username) return

    const password = EncryptSha256(
      `${userInfo.username}-${userInfo.phone}-${undefined}-${userInfo.belongCompany}` || '',
      H5_APP_SHA256_KEY,
    )

    tips.showLoading()
    const result = await api.AuthLogin({
      phone: userInfo?.phone,
      password,
    })

    if (result.success) {
      settingUser(result?.data)
    }

    tips.hideLoading()
  }

  /** 账号密码登录 */
  const login = async (params: LoginParams, hasEncrypt = true) => {
    const data = Object.assign({}, params)

    if (hasEncrypt) data.password = EncryptSha256(data.password || '', H5_APP_SHA256_KEY)
    tips.showLoading()
    const result = await api.SystemLogin(data)
    if (result.success) {
      settingUser(result?.data)

      await useDingding().ddRegister()
      // const permissionStore = usePermissionStore()
      // const deptSotre = useDeptStore()
      // await permissionStore.init()
      // await deptSotre.init()
      // await userStore.updateMessages()
    }
    // const { token, corpId, userInfo } = result.data;

    tips.hideLoading()
  }

  const checkAuth = async () => {
    if (isSync) return
    isSync = true
    return new Promise<string>(async (resolve) => {
      if (dd.env.platform !== 'notInDingTalk') {
        const code = await ddLogin.ddLogin()
        try {
          const result = await api.loginFreeByDingDingCode(code)
          if (result.success) {
            settingUser(result?.data)
            await useDingding().ddRegister()
            // const permissionStore = usePermissionStore()
            // await permissionStore.init()

            window.location.reload()
          }
        } catch {
          isSync = false
          resolve('-1')
        }
        isSync = false
        resolve('success')
      } else {
        isSync = false
        resolve('-1')
      }
    })
  }

  return {
    isLogin,
    register,
    verifyLogin,
    refreshLogin,
    login,
    checkAuth,
  }
}
